<template>
    <div>
        <el-drawer
            v-model="dialogRef.visible"
            :title="dialogRef.title"
            size="70%"
            @close="handleCloseDialog"
        >
            <el-form
                ref="dataFormRef"
                :model="formDataRef"
                :rules="computedRules"
                label-width="100px"
                :inline="true"
            >
                <el-card shadow="never">
                    <el-form-item label="字典名称" prop="name">
                        <el-input
                            v-model="formDataRef.name"
                            placeholder="请输入字典名称"
                        />
                    </el-form-item>
                    <el-form-item label="字典编码" prop="code">
                        <el-input
                            v-model="formDataRef.code"
                            placeholder="请输入字典编码"
                        />
                    </el-form-item>

                    <el-form-item label="状态">
                        <el-radio-group v-model="formDataRef.status">
                            <el-radio :value="1">启用</el-radio>
                            <el-radio :value="0">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-card>

                <el-card shadow="never" class="mt-5">
                    <template #header>
                        <div class="flex-x-between">
                            <span>字典项</span>
                            <el-button
                                type="primary"
                                size="small"
                                @click.stop="handleAddAttrClick"
                                ><i-ep-plus />新增字典</el-button
                            >
                        </div>
                    </template>
                    <el-table
                        v-loading="loadingRef"
                        highlight--currentrow
                        :data="formDataRef.dictItems"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column label="字典项名称" width="200">
                            <template #default="scope">
                                <el-form-item
                                    :prop="
                                        'dictItems.' + scope.$index + '.name'
                                    "
                                >
                                    <el-input v-model="scope.row.name" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="字典项值" width="200">
                            <template #default="scope">
                                <el-form-item
                                    :prop="
                                        'dictItems.' + scope.$index + '.value'
                                    "
                                >
                                    <el-input v-model="scope.row.value" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="排序">
                            <template #default="scope">
                                <el-form-item
                                    :prop="
                                        'dictItems.' + scope.$index + '.sort'
                                    "
                                >
                                    <el-input v-model="scope.row.sort" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" prop="status">
                            <template #default="scope">
                                <el-form-item
                                    :prop="
                                        'dictItems.' + scope.$index + '.status'
                                    "
                                >
                                    <el-switch
                                        v-model="scope.row.status"
                                        :active-value="1"
                                        :inactive-value="0"
                                    />
                                </el-form-item>
                            </template>
                        </el-table-column>

                        <el-table-column
                            fixed="right"
                            label="操作"
                            align="center"
                            width="120"
                        >
                            <template #default="scope">
                                <el-button
                                    type="danger"
                                    link
                                    size="small"
                                    @click.stop="
                                        handleDeleteAttrClick(scope.$index)
                                    "
                                    ><i-ep-delete />删除</el-button
                                >
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmitClick"
                        >确 定</el-button
                    >
                    <el-button @click="handleCloseDialog">取 消</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>
<script setup lang="ts">
import { TypeDictFormI } from '@/api/dict/dict_types';
import { computed, ref } from 'vue';
import * as dictApi from '@/api/dict/dict_api_index'
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import { $bus } from '@/event_bus/event_bus_index';

////#region defineXxx
//defineOptions({
//name:
//});

//const props=defineProps({
//propA:{
//type:String,
//required:true
//},
//propB:{
//type:Number,
//default:1
//},
//propC:{
//type:String as PropType<MyType>,
//required:true
//},
//});

//const emit = defineEmits<{
//event1:[para1:number,para2:string],
//event2:[para1:number,para2:string],
//}>();
////#endregion

// 字典弹窗
const dialogRef = ref({
  title: "",
  visible: false,
});

const dataFormRef = ref(ElForm);
const idsRef = ref<number[]>([]);


const formDataInit:TypeDictFormI={
    id:undefined,
    name:undefined,
    dictItems:[]
}

const formDataRef = ref<TypeDictFormI>({});
const loadingRef = ref(false);
const computedRules = computed(() => {
  const rules: Partial<Record<string, any>> = {
    name: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
    code: [{ required: true, message: "请输入字典编码", trigger: "blur" }],
  };
  if (formDataRef.value.dictItems) {
    formDataRef.value.dictItems.forEach((_attr:any, index:any) => {
      rules[`dictItems.${index}.name`] = [
        { required: true, message: "请输入字典项名称", trigger: "blur" },
      ];
    });
  }
  return rules;
});

// 行选择
function handleSelectionChange(selection: any) {
    idsRef.value = selection.map((item: any) => item.id);
}

// 新增字典
function handleAddClick() {
  
  dialogRef.value.visible = true;
  dialogRef.value.title = "新增字典";
  formDataRef.value=Object.assign({},formDataInit);
  formDataRef.value.dictItems!.length=0;
  dataFormRef.value.resetFields();
}


//打开drawer
function openDrawDialog(id?: number, name?: string){
    if(id && name){
        handleEditClick(id,name)
    }else{
        handleAddClick();
    }
}

/**
 * 编辑字典
 *
 * @param id 字典ID
 */
function handleEditClick(id: number, name: string) {
    dialogRef.value.visible = true;
    dialogRef.value.title = "【" + name + "】字典修改";
    // dataFormRef.value.resetFields();
    dictApi.getFormData(id).then(({data}) => {
    
    Object.assign(formDataRef.value, data);
    console.log('formDataRef.value',formDataRef.value);
  });
}

// 提交字典表单
function handleSubmitClick() {
    dataFormRef.value.validate((isValid: boolean) => {
    console.log("isValid", isValid);
    if (isValid) {
      loadingRef.value = true;
      const id = formDataRef.value.id;
      if (id) {
        dictApi.update(id, formDataRef.value)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            $bus.emit('dict-type-table-query');
          })
          .finally(() => (loadingRef.value = false));
      } else {
        dictApi.add(formDataRef.value)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            $bus.emit('dict-type-table-query');
          })
          .finally(() => (loadingRef.value = false));
      }
    }
  });
}

// dict-type-table-query
// dict-type-reset-and-query

/** 关闭字典弹窗 */
function handleCloseDialog() {
  dialogRef.value.visible = false;

  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formDataRef.value.id = undefined;
}



// 新增字典
function handleAddAttrClick() {
  formDataRef.value.dictItems = formDataRef.value.dictItems ?? [];
  formDataRef.value.dictItems.push({ sort: 1, status: 1 });
}
// 删除字典
function handleDeleteAttrClick(index: number) {
  if (formDataRef.value.dictItems && formDataRef.value.dictItems.length > 0) {
    formDataRef.value.dictItems.splice(index, 1);
  }
}
defineExpose({
    openDrawDialog
})

</script>
<style lang="scss" scoped></style>
